package cn.cdzdjd.resolver;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import cn.cdzdjd.annotation.LoginUser;
import cn.cdzdjd.dto.form.LoginForm;
import cn.cdzdjd.entity.UserSession;
import cn.cdzdjd.service.UserSessionService;
import cn.cdzdjd.util.UserHolder;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 *
 * @author
 */
@Component
@AllArgsConstructor
@Slf4j
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
	private final UserSessionService userSessionService;

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		log.info("请求方法携带参数类型:{}",parameter.getParameterType());
		return parameter.getParameterType().isAssignableFrom(LoginForm.class)
				&& parameter.hasParameterAnnotation(LoginUser.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request,
			WebDataBinderFactory factory) throws Exception {
		// 获取用户ID
		Long userId = UserHolder.getHolder();
		if (userId == null) {
			return null;
		}
		// 获取用户信息
		UserSession user = userSessionService.findById(userId);
		return user;
	}
}
